<template>
  <div>
    <button @click="start">开始录音</button>
    <button @click="stop">停止录音</button>
  </div>
</template>

<script>
import { AlawEncoder } from '@/utils/alaw-encoder';
import {audioFileSend} from "@/api/videoPlay";
export default {
  data() {
    return {
      stream: null,
      audioContext: null,
      scriptProcessor: null,
      chunks: [],
    };
  },
  methods: {
    async start() {
      this.stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
      const source = this.audioContext.createMediaStreamSource(this.stream);

      this.scriptProcessor = this.audioContext.createScriptProcessor(4096, 1, 1);
      this.scriptProcessor.onaudioprocess = (event) => {
        const inputBuffer = event.inputBuffer.getChannelData(0);
        this.chunks.push(new Float32Array(inputBuffer));
      };

      source.connect(this.scriptProcessor);
      this.scriptProcessor.connect(this.audioContext.destination);
    },
    stop() {
      if (this.scriptProcessor) {
        this.scriptProcessor.disconnect();
        this.scriptProcessor = null;
      }
      if (this.audioContext) {
        this.audioContext.close();
        this.audioContext = null;
      }
      if (this.stream) {
        this.stream.getTracks().forEach(track => track.stop());
        this.stream = null
      }

      const mergedChunks = this.mergeArrays(this.chunks);
      const wavData = this.encodeWAV(mergedChunks);

      const blob = new Blob([wavData], { type: 'audio/wav' });
      const formData = new FormData();
      formData.append('file', blob, 'recording.wav');
      formData.append('ip', '192.168.11.13');
      formData.append('port', '8000');
      formData.append('username', 'admin');
      formData.append('password', 'ucan1588');

      audioFileSend(formData).then(res=>{
        console.log(res, '================================')
        this.chunks = []
      })

      return
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'recording.wav';
      a.click();
      URL.revokeObjectURL(url);
    },
    encodeWAV(samples, sampleRate = 44100) {
      const buffer = new ArrayBuffer(44 + samples.length * 2);
      const view = new DataView(buffer);

      this.writeString(view, 0, 'RIFF');
      view.setUint32(4, 36 + samples.length * 2, true);
      this.writeString(view, 8, 'WAVE');
      this.writeString(view, 12, 'fmt ');
      view.setUint32(16, 16, true);
      view.setUint16(20, 1, true);
      view.setUint16(22, 1, true);
      view.setUint32(24, sampleRate, true);
      view.setUint32(28, sampleRate * 2, true);
      view.setUint16(32, 2, true);
      view.setUint16(34, 16, true);
      this.writeString(view, 36, 'data');
      view.setUint32(40, samples.length * 2, true);

      this.floatTo16BitPCM(view, 44, samples);

      return view;
    },
    writeString(view, offset, string) {
      for (let i = 0; i < string.length; i++) {
        view.setUint8(offset + i, string.charCodeAt(i));
      }
    },
    floatTo16BitPCM(view, offset, input) {
      for (let i = 0; i < input.length; i++, offset += 2) {
        const s = Math.max(-1, Math.min(1, input[i]));
        view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);
      }
    },
    mergeArrays(arrays) {
      const totalLength = arrays.reduce((acc, array) => acc + array.length, 0);
      const result = new Float32Array(totalLength);
      let offset = 0;
      for (const array of arrays) {
        result.set(array, offset);
        offset += array.length;
      }
      return result;
    },
  },
};
</script>
